package com.hbnu.mysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 需求：使用JDBC进行数据库表的增、删、改操作
 *
 * @author kittychen
 * @since 2025-10-20 10:23
 */
public class JdbcDemo01 {

    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        try {
            // 1、注册驱动
            // DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
            Class.forName("com.mysql.cj.jdbc.Driver");  // 驱动注册的第二种方式：通过反射注册驱动（重点掌握）

            // 2、获取数据库连接
            String url = "jdbc:mysql://127.0.0.1:3306/class2309?serverTimezone=GMT&useSSL=false";
            String username = "root";
            String password = "123456";
            connection = DriverManager.getConnection(url, username, password);  // 数据库连接对象

            // System.out.println(connection);
            // 3、获取数据库操作对象
            statement = connection.createStatement();

            // 4、执行SQL语句
            // String sql = "insert into tb_user(id, username, password, salary) values(1, 'zhangsan', '123456', 8000.52)";  // 往数据库表tb_user中插入数据
            // String sql = "delete from tb_user where id = 1";   // 根据id删除数据
            String sql = "update tb_user set salary = 15000 where id = 1";   // 根据id更新数据
            int row = statement.executeUpdate(sql);

            // System.out.println(row == 1 ? "插入成功" : "插入失败");
            // System.out.println(row == 1 ? "删除成功" : "删除失败");
            System.out.println(row == 1 ? "更新成功" : "更新失败");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 6、释放资源
            try {
                if (statement != null) {
                    statement.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }


        }
    }
}
